//
//  FiendFriend.m
//  MooreDoll
//
//  Created by 郭景豪 on 2014/12/11.
//  Copyright (c) 2014年 Tank. All rights reserved.
//

#import "FiendFriend.h"
#import "WinkAlertView.h"
#include "libxclient.h"

@implementation FiendFriend
{
    NSInteger fiendFriendResultsCount;
}

+(FiendFriend *)sharedInstance
{
    static FiendFriend *fiendFriend;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        fiendFriend = [[FiendFriend alloc] init];
        //先建立一個Vcard結果的陣列
        
        if (fiendFriend.vcardResultArray == nil) {
            fiendFriend.vcardResultArray = [[NSMutableArray alloc]initWithCapacity:0];
        }
        
    });
    
    return fiendFriend;
}

-(void)searchFreindForServer:(NSArray*)array
{
    
    AFHTTPRequestOperationManager *afManager = [AFHTTPRequestOperationManager manager];
    
    afManager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    afManager.responseSerializer.acceptableContentTypes = [afManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/plain"];
    
    NSDictionary *parameters = @{@"type":@"search",@"secret":@"openfire",@"phones":[FiendFriend changePhoneArrayToString:array]};
    
    
    [afManager POST:MD_SERVER_API parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"%@",responseObject);
        
        NSString *responseResult = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
        
        //成功
        if ([responseResult isEqualToString:@"0"]) {
            
            NSLog(@"%@",responseObject);
            if ([responseObject[@"user"]count]>0) {
                
                //將收到的 有在使用MD的好友陣列 添加連絡人名稱上去
                [self responseObjectFiendFriend:[FiendFriend source:array response:responseObject[@"user"]]];
                
            }else
            {
                [WinkAlertView _showAlertViewHaveDelegateWithTitle:@"失敗" content:@"未搜尋到朋友" cancelButtonTitle:@"確認" showTime:3.0f delegate:self];
            }
            
        }else
        {
            if (self.delegate && [self.delegate respondsToSelector:@selector(errorNotFindFriend)]) {
                [self.delegate errorNotFindFriend];
            }
            [WinkAlertView _showAlertViewWithTitle:@"失敗" content:responseObject[@"msg"] cancelButtonTitle:@"確認" showTime:3.0f];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        [self.delegate errorNotFindFriend];
        
        [WinkAlertView _showAlertViewWithTitle:@"失敗" content:@"網路連結失敗" cancelButtonTitle:@"確認" showTime:3.0f];
        
    }];
    
}

-(void)responseObjectFiendFriend:(id )responseObject
{
    NSLog(@"%@",responseObject);
    
    //這邊註冊朋友狀態結果的 delegate
    if ([XMPPSharedInstance sharedInstance].getFriendVcardDelegate != self) {
        
        [XMPPSharedInstance sharedInstance].getFriendVcardDelegate = self;
    }
    
    //清空狀態列表
    [self.vcardResultArray removeAllObjects];
    
    if (fiendFriendResultsCount == 0) {
        
        //拿搜尋朋友的jid 去要朋友的狀態
        for (id dict in responseObject) {
            
            //建立一個 vcard 要求的次數 int 當執行一次vcard 要求 就會自動+1
            fiendFriendResultsCount ++;
            NSLog(@"++++++++++%li",(long)fiendFriendResultsCount);
            
            //執行vcard 要求 並帶入 jid
            [[XMPPSharedInstance sharedInstance]getFriendVCard:dict[@"jid"]];
            
        }
        
        
        self.fiendFriendUseMDArray = [NSMutableArray arrayWithArray:responseObject];
        
    }
    
}
#pragma mark getFriendVcardResultDelegate
//好友列表取得的結果
-(void)getFriendVcardResult:(NSMutableDictionary *)fiendResults
{
    //建立一個 vcard 要求的次數 int 當收到vcard  就會自動 -1
    if (!fiendFriendResultsCount<=0) {
        fiendFriendResultsCount --;
        
        
        NSLog(@"--------%li",(long)fiendFriendResultsCount);
        
        //收到結果後 就加入一個陣列內
        [self.vcardResultArray addObject:fiendResults];
        
        
        //當收到的結果次數歸0的時候 就是完成了
        if (fiendFriendResultsCount == 0) {
            
            
            //將Vcard 陣列 添加到好友陣列裡面
            self.fiendFriendUseMDArray = [FiendFriend changeFriendUseMDarray:self.fiendFriendUseMDArray vcardResultArray:self.vcardResultArray];
            
            
            //當使用者如果有實現這個方法 就可以得到朋友清單狀態
            [self.delegate getVcardResult:self.fiendFriendUseMDArray];
        }
    }
}

//將Vcard 陣列 添加到好友陣列裡面
+(NSMutableArray *)changeFriendUseMDarray:(NSMutableArray *) friendUseMDArray vcardResultArray:(NSMutableArray *)vcardResultArray
{
    //vcard陣列
    [vcardResultArray enumerateObjectsUsingBlock:^(id vcard, NSUInteger idx, BOOL *stop) {
        
        NSLog(@"%@",vcard);
        //使用ＭＤ的彭有名單
        [friendUseMDArray enumerateObjectsUsingBlock:^(id useMD, NSUInteger idx, BOOL *stop) {
            
            //檢查名單相同的時候
            if ([vcard[@"vcard_get"]hasPrefix:useMD[@"jid"]]) {
                
                //把使用MD朋友的名單 添加vcard 進去
                NSArray *keys=[vcard allKeys];
                
                for(id key in keys){
                    [useMD setObject:[vcard objectForKey:key] forKey:key];
                }
                
            }
            
        }];
    }];
    return friendUseMDArray;
}

/*
 將陣列轉換成文字
 */
+(NSString *)changePhoneArrayToString:(NSArray *)array
{
    NSLog(@"%@",array);
    
    
    NSMutableArray *mutableArray = [[NSMutableArray alloc]initWithCapacity:0];
    
    for (id dict in array) {
        
        if ([dict objectForKey:@"phone"]) {
            [mutableArray addObject:[dict objectForKey:@"phone"]];
        }
    }
    NSString *string = [mutableArray componentsJoinedByString:@","];;
    
    return string;
}

/*
 將有在使用MD 的好友陣列 添加連絡人名稱上去
 */
+ (NSMutableArray *)source:(NSArray *)sourceArray response:(NSArray*)responseArray
{
    NSLog(@"%@",responseArray);
    
    //將陣列轉換成 mutable屬性
    NSMutableArray *result = [FiendFriend changeResponseObject:responseArray];
    
    [responseArray enumerateObjectsUsingBlock:^(id responsePhone, NSUInteger responseIdx, BOOL *stop) {
        
        [sourceArray enumerateObjectsUsingBlock:^(id sourcePhone, NSUInteger sourceIdx, BOOL *stop) {
            
            //MD
            NSString* responsePhoneString = responsePhone[@"phone"];
            //USER
            NSString* sourcePhoneString = sourcePhone[@"phone"];
            
            
            if ([responsePhoneString isEqualToString:sourcePhoneString]) {
                
                NSString *sourcePhoneName = sourcePhone[@"Name"];
                if (sourcePhoneName !=nil) {
                    [result[responseIdx] setObject:sourcePhoneName forKey:@"Name"];
                }
            }
            
        }];
    }];
    
    return result;
}

/*
 將網路收到的資料做一個轉換成 mutable 屬性
 */
+ (NSMutableArray *)changeResponseObject:(NSArray*)responseArray
{
    NSMutableArray *result = [[NSMutableArray alloc]initWithCapacity:[responseArray count]];
    
    //網路資料陣列拆解
    [responseArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        
        NSMutableDictionary *resDict=[[NSMutableDictionary alloc] initWithCapacity:[obj count]];     //新建一個NSMutableDictionary對象，大小為原NSDictionary對象的大小
        
        NSArray *keys=[obj allKeys];
        
        for(id key in keys){
            
            [resDict setObject:[obj objectForKey:key] forKey:key];
            
        }
        
        [result addObject:resDict];
    }];
    
    return result;
}




-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(errorNotFindFriend)]) {
        [self.delegate errorNotFindFriend];
        
    }
}



//}patrick


/*
 Search friend 搜尋朋友
 
 searchFriends
 POST parameters:
 type = "search"
 secret = "openfire"
 phones = "886.916123456,886.989123456,123456689212"  電話
 RESPONSE JSON string:
 No Mooredoll’s account: {"result":0,"user":[]"} 不存在
 Mooredoll’s account exist: {"result":0,"user":[{"phone":886.916123456","jid":"ce01394592464dc88860"}, {"phone":123456689212","jid":"7366f6038d7742ea9906"}]"} 存在
 */
@end
